package com.otitan.forest.right.util;

import cn.hutool.poi.excel.ExcelUtil;
import com.otitan.forest.right.dto.BssForestRightInfoEntityDto;
import com.otitan.forest.right.entity.BssForestRightInfoEntity;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class FileUtil {

    /**
     * excel表格直接下载
     */
    public static void exportExcelByDownload(XSSFWorkbook wb, HttpServletResponse response, String fileName) {

        // 设置response的Header
        setResponseContentDisposition(response, fileName);
        response.setContentType("application/octet-stream");
        try {
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

//        OutputStream stream = new BufferedOutputStream(response.getOutputStream());

        //输出流开始写出文件（FileUtils是Apache下的工具类可以直接调用）
//        stream.write(bytes);
        //刷新流
//        stream.flush();

    }

    public static void setResponseContentDisposition(HttpServletResponse response, String fileName) {
        // 清空response
        response.reset();

        // 创建显示内容
        StringBuilder contentDisposition = new StringBuilder("attachment;");
        // 如果附件不为null;
        if (fileName != null) {
            // 通过UTF8字符以及URL方式来编码文件名
            String filedisplay = fileName;
            try {
                filedisplay = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Ignore
            }
            // 添加标准文件名
            contentDisposition.append("filename=").append(fileName).append(";");
            // 添加UTF8格式名
            // 主要为了防止部分浏览器下的文件名乱码（参见https://tools.ietf.org/html/rfc6266）
            contentDisposition.append("filename*=utf-8''").append(filedisplay);
        }
        // 输出文件名
        response.addHeader("Content-Disposition", contentDisposition.toString());
    }

    /**
     * 下载服务指定路径的文件
     *
     * @param [response, filePath]
     * @return void
     * @throws
     * @author jiachangsen
     * @date 2020/08/12 16:25
     */
    public static void downloadFile(HttpServletResponse response, String filePath) {
        String fileName = "【错误信息】贵州省林权登记信息入库数字化表-" + DateUtil.getNowDateStr() + ".xlsx";
        try {
            // 文件的存放路径
            InputStream inStream = new FileInputStream(filePath);
            // 设置输出的格式
            setResponseContentDisposition(response, fileName);
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 下载导入的excel模板
     *
     * @param [response]
     * @return void
     * @throws
     * @author wangqingsong
     * @date 2020/08/13
     */
    public static void importFile(HttpServletResponse response) {

        try {
            String fileName = "【导入模板】贵州省林权登记信息入库数字化表-" + DateUtil.getNowDateStr() + ".xlsx";

            // 文件的存放路径
            InputStream inStream = ExcelUtil.class.getResourceAsStream("/excel/【导入模板】贵州省林权登记信息入库数字化表.xlsx");

            // 设置输出的格式
            setResponseContentDisposition(response, fileName);

            response.setContentType("application/octet-stream");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 为指定模板设置cell样式
     *
     * @param [xssfWorkbook]
     * @return XSSFCellStyle
     * @throws
     * @author wangqingsong
     */
    public static XSSFCellStyle setCellStyle(XSSFWorkbook xssfWorkbook) {
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setWrapText(true);//自动换行

        return cellStyle;
    }


    /**
     * 为指定模板设置样式和值
     *
     * @param [list,sheet,cellStyle]
     * @return void
     * @throws
     * @author wangqingsong
     */
    public static void setCellStyleAndValue(List<BssForestRightInfoEntityDto> list, XSSFSheet sheet, XSSFCellStyle cellStyle) throws IOException {
        for (int i = 0; i < list.size(); i++) {
            XSSFRow row1 = sheet.createRow(i + 3);

            XSSFCell cell = row1.createCell(0);
            cell.setCellValue(list.get(i).getGroundNo());
            cell.setCellStyle(cellStyle);

            XSSFCell cell1 = row1.createCell(1);
            cell1.setCellValue(list.get(i).getForestRightNo());
            cell1.setCellStyle(cellStyle);

            XSSFCell cell2 = row1.createCell(2);
            cell2.setCellValue(list.get(i).getRealUnitNo());
            cell2.setCellStyle(cellStyle);

            XSSFCell cell3 = row1.createCell(3);
            cell3.setCellValue(list.get(i).getCounty());
            cell3.setCellStyle(cellStyle);

            XSSFCell cell4 = row1.createCell(4);
            cell4.setCellValue(list.get(i).getTown());
            cell4.setCellStyle(cellStyle);

            XSSFCell cell5 = row1.createCell(5);
            String village = list.get(i).getVillage();
            cell5.setCellValue(village);
            cell5.setCellStyle(cellStyle);

            XSSFCell cell6 = row1.createCell(6);
            cell6.setCellValue(list.get(i).getGroupName());
            cell6.setCellStyle(cellStyle);

            XSSFCell cell7 = row1.createCell(7);
            cell7.setCellValue(list.get(i).getLandBelongUser());
            cell7.setCellStyle(cellStyle);

            XSSFCell cell8 = row1.createCell(8);
            cell8.setCellValue(list.get(i).getLandBelongUserCreditCode());
            cell8.setCellStyle(cellStyle);

            XSSFCell cell9 = row1.createCell(9);
            cell9.setCellValue(list.get(i).getLandUseUser());
            cell9.setCellStyle(cellStyle);

            XSSFCell cell10 = row1.createCell(10);
            cell10.setCellValue(list.get(i).getLandUseUserIdNo());
            cell10.setCellStyle(cellStyle);

            if (list.get(i).getLandUseStartDate() == null) {
                XSSFCell cell11 = row1.createCell(11);
                cell11.setCellValue("");
                cell11.setCellStyle(cellStyle);
            } else {
                XSSFCell cell11 = row1.createCell(11);
                cell11.setCellValue(dateToString(list.get(i).getLandUseStartDate()));
                cell11.setCellStyle(cellStyle);
            }

            XSSFCell cell12 = row1.createCell(12);
            cell12.setCellValue(list.get(i).getLandManageUser());
            cell12.setCellStyle(cellStyle);

            XSSFCell cell13 = row1.createCell(13);
            cell13.setCellValue(list.get(i).getLandManageUserIdNo());
            cell13.setCellStyle(cellStyle);

            XSSFCell cell14 = row1.createCell(14);
            cell14.setCellValue(list.get(i).getLandManageUserCreditCode());
            cell14.setCellStyle(cellStyle);

            if (list.get(i).getLandManageStartDate() == null) {
                XSSFCell cell15 = row1.createCell(15);
                cell15.setCellValue("");
                cell15.setCellStyle(cellStyle);
            } else {
                XSSFCell cell15 = row1.createCell(15);
                cell15.setCellValue(dateToString(list.get(i).getLandManageStartDate()));
                cell15.setCellStyle(cellStyle);
            }

            if (list.get(i).getLandManageEndDate() == null) {
                XSSFCell cell16 = row1.createCell(16);
                cell16.setCellValue("");
                cell16.setCellStyle(cellStyle);
            } else {
                XSSFCell cell16 = row1.createCell(16);
                cell16.setCellValue(dateToString(list.get(i).getLandManageEndDate()));
                cell16.setCellStyle(cellStyle);
            }

            XSSFCell cell17 = row1.createCell(17);
            cell17.setCellValue(list.get(i).getTreesBelongUser());
            cell17.setCellStyle(cellStyle);

            XSSFCell cell18 = row1.createCell(18);
            cell18.setCellValue(list.get(i).getTreesBelongUserIdNo());
            cell18.setCellStyle(cellStyle);

            XSSFCell cell19 = row1.createCell(19);
            cell19.setCellValue(list.get(i).getTreesBelongUserCreditCode());
            cell19.setCellStyle(cellStyle);

            XSSFCell cell20 = row1.createCell(20);
            cell20.setCellValue(list.get(i).getTreesUseUser());
            cell20.setCellStyle(cellStyle);

            XSSFCell cell21 = row1.createCell(21);
            cell21.setCellValue(list.get(i).getTreesUseIdNo());
            cell21.setCellStyle(cellStyle);

            XSSFCell cell22 = row1.createCell(22);
            cell22.setCellValue(list.get(i).getTreesUseCreditCode());
            cell22.setCellStyle(cellStyle);

            XSSFCell cell23 = row1.createCell(23);
            cell23.setCellValue(list.get(i).getCompartment());
            cell23.setCellStyle(cellStyle);

            XSSFCell cell24 = row1.createCell(24);
            cell24.setCellValue(list.get(i).getSubCompartment());
            cell24.setCellStyle(cellStyle);

            if (list.get(i).getArea() == null) {
                XSSFCell cell25 = row1.createCell(25);
                cell25.setCellValue("");
                cell25.setCellStyle(cellStyle);
            } else {
                XSSFCell cell25 = row1.createCell(25);
                cell25.setCellValue(list.get(i).getArea().toString());
                cell25.setCellStyle(cellStyle);
            }

            if (list.get(i).getNum() == null) {
                XSSFCell cell26 = row1.createCell(26);
                cell26.setCellValue("");
                cell26.setCellStyle(cellStyle);
            } else {
                XSSFCell cell26 = row1.createCell(26);
                cell26.setCellValue(list.get(i).getNum().toString());
                cell26.setCellStyle(cellStyle);
            }

            XSSFCell cell27 = row1.createCell(27);
            cell27.setCellValue(list.get(i).getTreeSpecies());
            cell27.setCellStyle(cellStyle);

            XSSFCell cell28 = row1.createCell(28);
            cell28.setCellValue(list.get(i).getForestCategory());
            cell28.setCellStyle(cellStyle);

            XSSFCell cell29 = row1.createCell(29);
            cell29.setCellValue(list.get(i).getAnnotation());
            cell29.setCellStyle(cellStyle);

            XSSFCell cell30 = row1.createCell(30);
            cell30.setCellValue(list.get(i).getSubPlaceName());
            cell30.setCellStyle(cellStyle);

            XSSFCell cell31 = row1.createCell(31);
            cell31.setCellValue(list.get(i).getBorderEast());
            cell31.setCellStyle(cellStyle);

            XSSFCell cell32 = row1.createCell(32);
            cell32.setCellValue(list.get(i).getBorderSouth());
            cell32.setCellStyle(cellStyle);

            XSSFCell cell33 = row1.createCell(33);
            cell33.setCellValue(list.get(i).getBorderWest());
            cell33.setCellStyle(cellStyle);

            XSSFCell cell34 = row1.createCell(34);
            cell34.setCellValue(list.get(i).getBorderNorth());
            cell34.setCellStyle(cellStyle);

            XSSFCell cell35 = row1.createCell(35);
            cell35.setCellValue(list.get(i).getStatusToString().toString());
            cell35.setCellStyle(cellStyle);

            XSSFCell cell36 = row1.createCell(36);
            cell36.setCellValue(list.get(i).getRemark());
            cell36.setCellStyle(cellStyle);

        }

    }

    public static String dateToString(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        String str = simpleDateFormat.format(date);
        return str;
    }


    public static void exportMdb(HttpServletResponse response, String filePath) {

        try {
            String fileName = "林权登记信息表-" + DateUtil.getNowDateStr() + ".mdb";

            // 文件的存放路径
            FileInputStream fis = new FileInputStream(filePath);

            // 设置输出的格式
            setResponseContentDisposition(response, fileName);

            response.setContentType("application/octet-stream");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

